package org.meb.speedway.process.sf;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.regex.Pattern;

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.NullWriter;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.DefaultHttpClient;
import org.meb.speedway.model.common.IntEvent;
import org.meb.speedway.process.EventTaskProcessException;
import org.meb.speedway.process.EventTaskProcessor;
import org.meb.speedway.process.model.EventData;

public class SFEventTaskProcessor implements EventTaskProcessor {

	private static final String EVENT_URI_BASE = "www.sportowefakty.pl/zuzel/wydarzenie/";
	private static final String EVENT_SCORE_URI_BASE = "www.sportowefakty.pl/mini/";
	private static final Pattern pattern = Pattern.compile("(?i)(?:http://)?" + EVENT_URI_BASE
			+ "[0-9]{1,5}");

	private DefaultHttpClient httpClient;
	private SFEventParser eventParser;

	public SFEventTaskProcessor() {
		httpClient = new DefaultHttpClient();
		eventParser = new SFEventParserChain();
	}

	public boolean canProcess(IntEvent task) {
		return pattern.matcher(task.getEventUri()).matches();
	}

	public EventData process(IntEvent eventTask) throws EventTaskProcessException {
		return process(eventTask, NullWriter.NULL_WRITER);
	}

	public EventData process(IntEvent eventTask, Writer logWriter)
			throws EventTaskProcessException {
		// PrintWriter logPrintWriter = new PrintWriter(logWriter);
		if (!canProcess(eventTask)) {
			throw new IllegalArgumentException("Cannot process task");
		}

		EventData eventData = processEventHttpRequest(eventTask);
		processEventScoreHttpRequest(eventTask, eventData);
		return eventData;
	}

	private EventData processEventHttpRequest(IntEvent eventTask) throws EventTaskProcessException {
		try {
			URI uri = new URIBuilder(eventTask.getEventUri()).build();
			HttpResponse response = httpClient.execute(new HttpGet(uri));
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				Charset charset = ContentType.getOrDefault(response.getEntity()).getCharset();
				InputStream content = response.getEntity().getContent();
				InputStreamReader reader = new InputStreamReader(content, charset);
				StringWriter writer = new StringWriter();
				IOUtils.copy(reader, writer);
				IOUtils.closeQuietly(content);
				return eventParser.parse(writer.toString());
			}
			return null;
		} catch (Exception e) {
			throw new EventTaskProcessException(e);
		}
	}

	private void processEventScoreHttpRequest(IntEvent eventTask, EventData eventData)
			throws EventTaskProcessException {
		int idx = eventTask.getEventUri().lastIndexOf('/');
		int id = Integer.parseInt(eventTask.getEventUri().substring(idx + 1));
		try {
			URI uri = new URIBuilder(EVENT_SCORE_URI_BASE).setParameter("app", "live_speedway")
					.setParameter("id", Integer.toString(id)).build();
			HttpResponse response = httpClient.execute(new HttpGet(uri));
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

			}
		} catch (Exception e) {
			throw new EventTaskProcessException(e);
		}
	}
}
